package service

import (
	"awesomeTask/application/client"
	"awesomeTask/application/models/taskLog"
	"awesomeTask/application/nodeServer"
	"awesomeTask/application/resource"
	"awesomeTask/application/task/RunningTask"
	"awesomeTask/application/variable"
	"awesomeTask/application/websocket"
	"awesomeTask/commom/MessageHelper"
	"awesomeTask/commom/StringHelper"
	"awesomeTask/commom/timeHelper"
	"awesomeTask/config"
	"awesomeTask/system/event"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	"awesomeTask/system/log"
	"awesomeTask/system/rpc"
	"fmt"
	"time"
)

type TaskService struct {
}

/**
注册服务器的定时任务
*/

func GetTaskManager() *RunningTask.RunningTask {
	instance := kernel.GetIocInstance()
	return instance.GetInstanceOrCreate("runningTaskManager").(*RunningTask.RunningTask)
}
func (ioc TaskService) Register() {
	instance := kernel.GetIocInstance()
	instance.BindCreateObject("runningTaskManager", func() interface{} {
		runningTask := RunningTask.RunningTask{}
		go runningTask.HandleBack()
		return &runningTask
	}, true)
	event.Register(variable.ON_FINISH_TASK_PY, func(args ...interface{}) {
		taskInfo := args[0].(map[string]interface{})["runningInfo"]
		event.Dispatch(variable.ON_LOG, taskInfo)
	})
	event.Register(variable.ON_RUN_TASK, func(args ...interface{}) interface{} {
		fmt.Println("开始执行任务=========================》")
		variable.CurrentRunningTaskNum += 1
		taskInfo := args[0].(map[string]interface{})["taskInfo"].(map[string]interface{})
		taskUniqueId := taskInfo["uniqueTaskId"].(string)
		taskInfo["host"] = "127.0.0.1"
		taskInfo["port"] = config.GetConfigByKey("nodePort")
		taskInfo["token"] = StringHelper.UniqueId(8)
		res := make(map[string]interface{})
		runSuccess := false
		event.RegisterOne(taskUniqueId, func(args ...interface{}) {
			res = args[0].(map[string]interface{})
			runSuccess = true
		})
		runTask := resource.RunTask(taskInfo["project_name"].(string), taskInfo, taskInfo["taskId"].(string))
		if runSuccess == false {
			time.Sleep(time.Second * 2)
		}
		variable.CurrentRunningTaskNum -= 1
		if !runSuccess {
			res["errno"] = variable.TASK_FORK_ERRNO
		}
		taskLog.UpdateLog(runTask.TaskLogId, runTask.Stdout.GetDataString(), runTask.Stderr.GetDataString(), timeHelper.NowInt()-runTask.StartAt, helper.JsonEncode(res))
		return res
	})

	event.Register(variable.ON_TASK_NODE_RESULT, func(args ...interface{}) {
		resultInfo := args[0].(map[string]interface{})
		taskId := resultInfo["taskId"].(string)
		resultMsg := make([]interface{}, 0)
		result := resultInfo["result"]
		switch result.(type) {
		case []interface{}:
			resultMsg = result.([]interface{})
			break
		default:
			resultMsg = append(resultMsg, result)
		}
		if resultInfo["content"].(map[string]interface{})["error"] != nil {
			log.GetLogger().Info("任务执行失败错误信息:" + resultInfo["content"].(map[string]interface{})["error"].(string))
		}
		println(taskId)
		//dds.GetDdsObj().Push(resultMsg, taskId)
	})

	event.Register(variable.ON_TASK_NODE_REMOTE_FORK, func(args ...interface{}) {
		params := args[0].(map[string]interface{})
		params["uniqueTaskId"] = StringHelper.UniqueId(10)
		//websocket.SendToAll(variable.ON_PUSH_TASK, message)
		res, err := rpc.RpcCall(variable.ON_TASK_NODE_REMOTE_FORK_TO_MASTER, params, client.GetServerCon(), 5000)
		fmt.Println(res, "执行结果")
		if err != nil {
			log.GetLogger().Error("子任务执行失败失败原因:" + err.Error())
			nodeServer.SendToTaskNode(params["pTaskId"].(string), variable.ON_CHILDREN_TASK_FINISHED, map[string]interface{}{
				"error": err.Error(),
			})
		} else {
			nodeServer.SendToTaskNode(params["pTaskId"].(string), variable.ON_CHILDREN_TASK_FINISHED, res.(map[string]interface{}))
		}
	})
	event.Register(variable.ON_TASK_NODE_REMOTE_FORK_TO_MASTER, func(args ...interface{}) interface{} {
		conn := client.GetBestNode()
		message := map[string]interface{}{
			"source":    config.GetConfigByKey("location"),
			"to":        conn.Location,
			"descIp":    config.GetConfigByKey("publicIP"),
			"taskId":    args[0].(map[string]interface{})["taskInfo"].(map[string]interface{})["uniqueTaskId"],
			"realEvent": variable.ON_PUSH_TASK,
		}
		websocket.SendToAllNodes(variable.ON_PUSH_TASK, message)
		res, err := rpc.RpcCall(variable.ON_RUN_TASK, args[0].(map[string]interface{})["taskInfo"].(map[string]interface{}), conn.Connetion, 5000)
		if err != nil {
			log.GetLogger().Info("远程调用执行失败" + err.Error())
		}
		return res
	})
	event.Register(variable.ON_TASK_REMOTE_FORK_TO_MASTER, func(args ...interface{}) interface{} {
		conn := client.GetBestNode()
		res, err := rpc.RpcCall(variable.ON_RUN_TASK, args[0].(map[string]interface{})["taskInfo"].(map[string]interface{}), conn.Connetion, 5000)
		if err != nil {
			log.GetLogger().Info("远程调用执行失败" + err.Error())
		}
		return res
	})
	event.Register(variable.ON_MASTER_SEND_TO_ALL_WS, func(args ...interface{}) {
		for _, con := range client.Nodes {
			MessageHelper.SendEvent(variable.ON_SEND_TO_ALL_WS_CLIENT, args[0].(map[string]interface{}), con.Connetion)
		}
	})
	event.Register(variable.ON_SEND_TO_ALL_WS_CLIENT, func(args ...interface{}) interface{} {
		params := args[0].(map[string]interface{})
		sendEvent := params["realEvent"].(string)
		params["event"] = sendEvent
		websocket.SendToAll(sendEvent, params)
		return ""
	})

}

func (ioc TaskService) Boot() {

}
